import AuthorInfo from '@/pages/Generator/Detail/components/AuthorInfo';
import FileConfig from '@/pages/Generator/Detail/components/fileConfig';
import ModelConfig from '@/pages/Generator/Detail/components/modelConfig';
import {
  downloadGeneratorByIdUsingGet,
  getGeneratorVoByIdUsingGet,
} from '@/services/backend/generatorController';
import { Link, useParams } from '@@/exports';
import { DownloadOutlined, EditOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Button, Card, Col, Image, message, Row, Space, Tabs, Tag, Typography } from 'antd';
import { saveAs } from 'file-saver';
import moment from 'moment';
import React, { useEffect, useState } from 'react';
import {useModel} from "@umijs/max";

// 代码生成器详情页
const GeneratorDetailPage: React.FC = () => {
  // 通过 useParams 钩子函数获取到动态路由的 id
  const { id } = useParams();
  const [loading, setLoading] = useState<boolean>(false);
  const [data, setData] = useState<API.GeneratorVO>({});
  const { initialState } = useModel('@@initialState');
  // 使用ant design组件获取当前用户
  const { currentUser } = initialState ?? {};
  // 判断当前是否为创建人登陆
  const my = currentUser?.id === data?.userId;

  const loadData = async () => {
    if (!id) {
      return;
    }

    setLoading(true);
    try {
      // @ts-ignore
      const res = await getGeneratorVoByIdUsingGet({ id });
      setData(res.data || {});
    } catch (error: any) {
      message.error('加载数据失败' + error.message);
    }
    setLoading(false);
  };

  // 钩子函数，当id发生变化时，触发loadData方法
  useEffect(() => {
    loadData();
  }, [id]);

  /**
   * 标签列表
   * @param tags
   */
  const tagListView = (tags?: string[]) => {
    // 为空返回空标签
    if (!tags) {
      return <></>;
    }

    // 遍历返回Tag标签修饰的tag数据
    return (
      <div style={{ marginBottom: 8 }}>
        {tags.map((tag) => (
          <Tag key={tag}>{tag}</Tag>
        ))}
      </div>
    );
  };

  /**
   * 下载按钮（只有存在 distPath 代码包并且登陆，才能下载）
   */
  const downloadButton = data.distPath && currentUser && (
    <Button
      icon={<DownloadOutlined />}
      loading={loading}
      //  点击按钮事件
      onClick={async () => {
        try {
          setLoading(true);
          const blob = await downloadGeneratorByIdUsingGet(
            {
              id: data.id,
            },
            {
              // responseType为blob让前端识别返回的数据为二进制文件
              responseType: 'blob',
            },
          );
          const fullPath = data.distPath || '';
          // 使用file-saver 来保存文件
          // lastIndexOf('/') + 1表示从最后一个/位置后（不包括该/）开始截取到该字符串末尾，即为该文件名
          saveAs(blob, fullPath.substring(fullPath.lastIndexOf('/') + 1));
        } finally {
          setLoading(false);
        }
      }}
    >
      下载
    </Button>
  );

  /**
   * 编辑按钮（只有创建者才能编辑）
   */
  const editButton = my && (
    <Link to={`/generator/update?id=${data.id}`}>
      <Button icon={<EditOutlined />}>编辑</Button>
    </Link>
  );

  return (
    <ProCard>
      {/*上下两个卡片*/}
      <Card>
        {/*一行中有两列，每列中间间隔空位，gutter={[水平间距,垂直间距]}*/}
        <Row justify="space-between" gutter={[32, 32]}>
          {/*该列所占空间自定义*/}
          <Col flex="auto">
            {/*Space中的标签组件和标题组件之间间隔large大小的空位，并且垂直居中*/}
            <Space size="large" align="center">
              <Typography.Title level={4}>{data.name}</Typography.Title>
              {tagListView(data.tags)}
            </Space>
            <Typography.Paragraph>{data.description}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">
              创建时间：{moment(data.createTime).format('YYYY-MM-DD hh:mm:ss')}
            </Typography.Paragraph>
            <Typography.Paragraph type="secondary">
              基础包名：{data.basePackage}
            </Typography.Paragraph>
            <Typography.Paragraph type="secondary">版本：{data.version}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">作者：{data.author}</Typography.Paragraph>
            {/*间隔*/}
            <div style={{ marginBottom: 24 }} />
            <Space size="middle">
              <Link to={`/generator/use/${id}`}>
                <Button type="primary">立即使用</Button>
              </Link>
              {downloadButton}
              {editButton}
            </Space>
          </Col>
          {/*该行所占空间固定为320像素*/}
          <Col flex="320px">
            <Image src={data.picture} />
          </Col>
        </Row>
      </Card>
      {/*间隔*/}
      <div style={{ marginBottom: 24 }} />
      <Card>
        {/*选项卡组件*/}
        <Tabs
          size="large"
          defaultActiveKey={'fileConfig'}
          onChange={() => {}}
          items={[
            {
              key: 'fileConfig',
              label: '文件配置',
              children: <FileConfig data={data} />,
            },
            {
              key: 'modelConfig',
              label: '模型配置',
              children: <ModelConfig data={data} />,
            },
            {
              key: 'userInfo',
              label: '作者信息',
              children: <AuthorInfo data={data} />,
            },
          ]}
        />
      </Card>
    </ProCard>
  );
};

export default GeneratorDetailPage;
